Page({
    data: {
        signPath: [],
        preX: '',
        preY: '',
        preShowImg: '',
        isOk: true,
        locationName: '',
        location: [],
        imageSrc: ''
    },
    onLoad () {
        let that = this;
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('service_Goin', function (data) {
            that.setData({
                isOk: data.service_Goin,
            })
        })
    },
    onShow () {
        wx.createSelectorQuery().select('#myCanvas').fields({ node: true, size: true }).exec(this.init.bind(this))
    },
    init (data) {
        const width = data[0].width;
        const height = data[0].height;
        const canvas = data[0].node;
        const ctx = canvas.getContext('2d');
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = width * dpr
        canvas.height = height * dpr
        ctx.scale(dpr, dpr)
        this._dpr = dpr
        this._ctx = ctx
        this._canvas = canvas
        ctx.fillStyle = '#ffffff';
        ctx.fillRect(0, 0, width, height);//绘制填充白色背景
    },
    touchStart (e) {
        const { _ctx: ctx } = this
        const { clientX: x, clientY: y } = e.touches[0]
        ctx.beginPath()
        ctx.moveTo(x - e.target.offsetLeft, y - e.target.offsetTop)
        this.setData({
            preX: x - e.target.offsetLeft,
            preY: y - e.target.offsetTop,
        })
    },
    touchMove (e) {
        const { _ctx: ctx } = this
        const { clientX: x, clientY: y } = e.touches[0]
        this.data.signPath.push([x, y])
        this.setData({
            signPath: this.data.signPath
        })
        let preX = this.data.preX
        let preY = this.data.preY
        let curX = x - e.target.offsetLeft
        let curY = y - e.target.offsetTop
        let deltaX = Math.abs(preX - curX)
        let deltaY = Math.abs(preY - curY)
        if (deltaX >= 3 || deltaY >= 3) {
            let centerX = (preX + curX) / 2
            let centerY = (preY + curY) / 2
            ctx.quadraticCurveTo(preX, preY, centerX, centerY);
            ctx.stroke();
            this.setData({
                preX: curX,
                preY: curY,
            })
        }
    },
    //重绘
    reset () {
        const { _ctx: ctx, _canvas: canvas } = this

        this.setData({
            signPath: []
        })
        ctx.clearRect(0, 0, canvas.width, canvas.height)
    },
    //提交签名图片
    sure () {
        if (this.data.signPath.length <= 0) {
            return wx.$toast('签名不能为空')
        }
        if (this.data.signPath.length <= 90) {
            return wx.$toast('签名过短,请详细一点')
        }
        //导出图片
        this.comeLocation()
    },
    sureSignature () {
        if (this.data.signPath.length <= 0) {
            return wx.$toast('签名不能为空')
        }
    },
    comeLocation () {
        let that = this
        wx.$comeLocation((res) => {
            if (res.latitude && res.longitude) {
                that.setData({
                    location: [res.latitude, res.longitude]
                }, () => {
                    wx.$getLocationAdd(`${res.latitude},${res.longitude}`, (data) => {
                        that.setData({
                            locationName: data.result.address
                        }, () => {
                            that.outImage()
                        })
                    })
                })
            }
        })
    },
    outImage () {
        wx.showLoading({})
        let that = this;
        const { _canvas: canvas } = this
        const eventChannel = this.getOpenerEventChannel();
        wx.canvasToTempFilePath({
            canvas: canvas,
            fileType: 'jpg',
            success: (res) => {
                var imageSrc = res.tempFilePath;
                wx.showLoading()
                if (that.data.isOk) {
                    that.addWaterMark(imageSrc).then(data => {
                        wx.hideLoading()
                        this.setData({ imageSrc, showImg: data.tempFilePath })
                        eventChannel.emit('getBindingImage', { showImg: data.tempFilePath });
                        wx.navigateBack({})
                    })
                } else {
                    that.addWaterMark(imageSrc).then(data => {
                        wx.hideLoading()
                        this.setData({ imageSrc, showImg: data.tempFilePath })
                        eventChannel.emit('getBindingImageOut', { showImg: data.tempFilePath });
                        wx.navigateBack({})
                    })
                }
            },
            complete () {
                wx.hideLoading()
            }
        }, this)
    },
    addWaterMark (tempFilePath) {
        return new Promise((resolve, reject) => {
            let that = this
            wx.createSelectorQuery().select('#mycanvasSrc').fields({
                node: true,
                size: true
            }).exec((res) => {
                const canvas = res[0].node;
                const ctx = canvas.getContext('2d');
                const imageSrc = tempFilePath;
                const times = wx.$util.formatTime(new Date());
                wx.getImageInfo({
                    src: imageSrc,
                    success: function (imageRes) {
                        canvas.width = imageRes.width;
                        canvas.height = imageRes.height;
                        that.setData({
                            canvasStyle: `width: ${imageRes.width}rpx;height: ${imageRes.height}rpx`
                        })
                        const image = canvas.createImage();
                        image.src = imageSrc;
                        image.onload = () => {
                            ctx.drawImage(image, 0, 0, imageRes.width, imageRes.height)
                            ctx.font = '30px Arial';
                            ctx.fillStyle = 'red';
                            ctx.strokeStyle = "black";
                            let filltextHeight = imageRes.height - (that.drawText(ctx, that.data.locationName, imageRes.width, imageRes.height - 35, 232, 750 / 5 * 5) * 35);
                            ctx.fillText(times, imageRes.width - (ctx.measureText(times).width + 30), filltextHeight);
                            ctx.restore();
                            setTimeout(() => {
                                wx.canvasToTempFilePath({
                                    canvas,
                                    fileType: 'jpg',
                                    success: function (res) {
                                        resolve(res)
                                    },
                                    fail: function (res) {
                                        reject(res)
                                    }
                                }, this);
                            }, 1000);
                        }

                    },
                    fail: function (imageRes) {
                        wx.hideLoading()
                        console.log(imageRes, '错误了');
                    }
                });
            });
        })
    },
    // 绘画字体 判断是否文字过多分行
    drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
        var lineWidth = 0;
        var lastSubStrIndex = 0;
        var heightLineNum = 0;
        for (let i = 0; i < str.length; i++) {
            lineWidth += ctx.measureText(str[i]).width;
            if (lineWidth > canvasWidth) {
                heightLineNum++;
                var title = str.substring(lastSubStrIndex, i);
                var leftWidthNum = leftWidth - ctx.measureText(title).width - 30;
                ctx.fillText(title, leftWidthNum, initHeight);
                initHeight -= 30;
                lineWidth = 0;
                lastSubStrIndex = i;
                titleHeight += 30;
            }
            if (i == str.length - 1) {
                var title = str.substring(lastSubStrIndex, i + 1);
                var leftWidthNum = leftWidth - ctx.measureText(title).width - 30
                heightLineNum++;
                ctx.fillText(title, leftWidthNum, initHeight);
            }
        }
        titleHeight = titleHeight + 10;
        return heightLineNum + 1
    },
    showImage () {
        let that = this
        wx.previewImage({
            urls: [that.data.imageSrc],
        })
    },
    showImages () {
        let that = this
        wx.previewImage({
            urls: [that.data.showImg],
        })
    }
})
